package me.hunche.app.service.impl;

import java.util.HashMap;
import java.util.Map;

import me.hunche.app.exception.ServiceException;
import me.hunche.app.service.ShortUrlService;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Service;

import com.hp.hpl.helper.misc.WebServiceHelper;

@Service
public class ChinaTelecomShortUrlService implements ShortUrlService{

	public String long2short(String longUrl) {
		Map<String,String> parameters = new HashMap<String,String>();
		parameters.put("longurl", longUrl);
		String resp = WebServiceHelper.postJsonRequest("http://api.189.cn/EMP/shorturl/long2short", parameters, 5*1000, 5*1000);
		try {
			Document doc = DocumentHelper.parseText(resp);
			Element root = doc.getRootElement();
			String resCode = root.element("res_code").getText();
			if(!"0".equals(resCode)){
				throw new ServiceException("long2short faild! res_code="+resCode +",res_message="+ root.element("res_message").getText());
			}
			return root.elementText("shorturl");
		} catch (DocumentException e) {
			e.printStackTrace();
			throw new ServiceException("long2short faild!caused by parse resp:"+resp);
		}  
	}

	public String short2long(String longUrl) {
		// TODO Auto-generated method stub
		return null;
	}

}
